const app = getApp()

const Base64 = require('./Base64.js');
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

const uploadFile = function (filePath, dir, successc, failc) {
  if (!filePath || filePath.length < 9) {
    switch (dir) {
      case 'images/':
        wx.showModal({
          title: '图片错误',
          content: '请重试',
          showCancel: false,
        })
        break;
      case 'audio/':
        wx.showModal({
          title: '音频错误',
          content: '请重试',
          showCancel: false,
        })
        break;
      default:
    }
    return;
  }

  console.log('上传文件…');
  const token = wx.getStorageSync('token')
  app.http({
    config: { url: '/api/User/aliyun_oss_config', data: { token }, method: 'POST' },
    isAuth: false
  }).then(res => {
    console.log(res, 'ossRes')
    const data = res.data.data
    const uploadImageUrl = data.upload_url; // OSS地址，需要https
    const AccessKeySecret = data.access_key;
    const OSSAccessKeyId = data.access_id;
    const timeout = 87600; // 这个是上传文件时Policy的失效时间
    const policyBase64 = getPolicyBase64(timeout);
    const signature = getSignature(policyBase64, AccessKeySecret); // 获取签名
    const fileName = filePath.lastIndexOf("."); // 文件路径开始到最后一个点的长度
    const fileNameLength = filePath.length; // 文件路径长度
    const fileFormat = filePath.substring(fileName, fileNameLength); // 文件后缀
    const aliyunFileKey = data.url + dir + Date.parse(new Date()) + parseInt((Math.random() * 10000)) + fileFormat; // 文件上传到阿里云服务器上的名字，data.url是后端返回的目录（这里后端返回data.url的示例：upload/2020-08-03/，日期格式文件夹，存放当天上传的文件。注意：upload前面一定不能有'/'，否则会导致文件上传失败），dir是前端设置的目录（作用：不同类型的文件可以存在不同目录下，便于管理。例：images/ 目录用来存放图片文件，audios/ 目录用来存放音频文件），两个目录拼接成文件最终要上传到阿里云的目录，文件名是时间戳拼接随机数组成，保证文件名的唯一性，fileFormat是文件后缀名
    /*console.log(uploadImageUrl, 'uploadImageUrl')
    console.log(filePath, 'filePath')
    console.log(aliyunFileKey, 'aliyunFileKey')
    console.log(policyBase64, 'policyBase64')
    console.log(OSSAccessKeyId, 'OSSAccessKeyId')
    console.log(signature, 'signature')*/
    wx.uploadFile({
      url: uploadImageUrl,
      filePath: filePath,
      name: 'file', //必须填file
      formData: {
        'key': aliyunFileKey,
        'policy': policyBase64,
        'OSSAccessKeyId': OSSAccessKeyId,
        'signature': signature,
        'success_action_status': '200',
      },
      success: function (res) {
        console.log(res)
        if (res.statusCode != 200) {
          failc(new Error('上传错误:' + JSON.stringify(res)))
          return;
        }
        successc(aliyunFileKey);
      },
      fail: function (err) {
        console.log('上传图片失败', err)
        err.wxaddinfo = uploadImageUrl;
        failc(err);
      },
    })
  }).catch(err => {
    console.log(err, 'ossErr')
  })
}

const getPolicyBase64 = function (timeout) {
  let date = new Date();
  date.setHours(date.getHours() + timeout);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
    "conditions": [
      ["content-length-range", 0, 100 * 1024 * 1024] // 设置上传文件的大小限制,100mb
    ]
  };
  const policyBase64 = Base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64, AccessKeySecret) {
  const accesskey = AccessKeySecret;
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);
  return signature;
}

module.exports = uploadFile;
